#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import hashlib
import datetime
import json
import string

__author__ = 'Eric'

import random


def random_str(randomlength=8):
    str = ''
    # chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    length = len(chars) - 1
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


def random_int(randomlength=6):
    str = ''
    # chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    chars = '0123456789'
    length = len(chars) - 1
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


def md5hex(word):
    """ MD5加密算法，返回32位小写16进制符号 """
    if isinstance(word, unicode):
        word = word.encode("utf-8")
    elif not isinstance(word, str):
        word = str(word)
    m = hashlib.md5()
    m.update(word)
    return m.hexdigest()


def generate_code():
    """
    :return string(14)
    """
    now = datetime.datetime.now()

    return now.strftime("%Y%m%d%H%M%S")[4:][:-1]


def generate_trade_time(expire_days=None):
    """
    :return string(14)
    """
    now = datetime.datetime.now()

    if expire_days is not None:
        now = now + datetime.timedelta(days=expire_days)

    return now.strftime("%Y%m%d%H%M%S")


def generate_nonce_str(size=32, chars=string.uppercase + string.digits):
    """
    # generate nonce str
    """
    return ''.join(random.SystemRandom().choice(chars) for _ in xrange(0, size))
